package team.hyznrj.studentsys.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import team.hyznrj.studentsys.constant.CookieConstant;
import team.hyznrj.studentsys.dao.mapper.CollegeMajorMapper;
import team.hyznrj.studentsys.entity.account.AccountInfo;
import team.hyznrj.studentsys.interceptor.LoginInterceptor;
import team.hyznrj.studentsys.utils.CookieUtil;
import team.hyznrj.studentsys.utils.RedisUtil;
import team.hyznrj.studentsys.wrapper.RequestParameterWrapper;

/**
 * 
 * 
 * 过滤器会过滤全部元素，与需求不同，改用拦截器
 * @see team.hyznrj.studentsys.interceptor.LoginInterceptor
 * @author 郑泽锋
 * @date 2018年9月10日
 */
//@WebFilter
@Deprecated
public class LoginFilter implements Filter {
	@Autowired
	RedisUtil redisUtil;
	@Autowired
	CollegeMajorMapper mapper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) servletRequest;
		String url = request.getServletPath();
		System.out.println("require url:"+url);
		if(url.matches("/account/login")||url.matches("/swagger-resources/*")){
			chain.doFilter(servletRequest, response);
			System.out.println("return...");
			return ;
		}
		Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
		if (cookie == null || StringUtils.isEmpty(cookie.getValue())) {
			return;
		}
		String tokenValue = cookie.getValue();

		if (tokenValue == null) {
			return;
		}

		AccountInfo account = redisUtil.getAccount(cookie.getValue());

		if (account == null) {
			return;
		}
		 RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request);
		String flag = mapper.getFlag(account.getCollegeMajorId()) + account.getId();
		Map<String,Object> attributes=new HashMap<>();
		attributes.put("flag", flag);
		requestParameterWrapper.addParameters(attributes);
		System.out.println("参数flag传入..");
		chain.doFilter(requestParameterWrapper, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
